﻿using Antares.VIEWMODELs;
using AntaresShell.Common;
using AntaresShell.Common.MessageTemplates;
using AntaresShell.Logger;
using AntaresShell.NavigatorProvider;
using Repository.MODELs;
using Repository.Sync;
using System;
using Windows.System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace Antares.VIEWs
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class AddTask
    {
        public AddTask()
        {

            InitializeComponent();
            cancelButton.Tapped += CancelButtonOnTapped;
            StDate.ValueChanged += StDateOnValueChanged;
            Period.LayoutUpdated += Period_LayoutUpdated;
            Period.KeyDown += Period_KeyDown;
            Period.LostFocus += Period_LostFocus;

            CboCategory.LayoutUpdated += CboCategory_LayoutUpdated;
            CboProject.LayoutUpdated += CboProject_LayoutUpdated;
            CboAssignee.LayoutUpdated += CboAssignee_LayoutUpdated;

            CboCategory.DropDownOpened += CboCategory_DropDownOpened;
            CboProject.DropDownOpened += CboProjectOnDropDownOpened;
            CboAssignee.DropDownOpened += CboAssigneeOnDropDownOpened;
        }

        void Period_LostFocus(object sender, RoutedEventArgs e)
        {
            if (Period.Text == "" || Period.Text == "0")
            {
                Period.Text = "0.5";
            }
        }

        void Period_KeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (!e.Key.ToString().Equals("190"))
            {
                switch (e.Key)
                {
                    case VirtualKey.Decimal:
                    case VirtualKey.Number0:
                    case VirtualKey.Number1:
                    case VirtualKey.Number2:
                    case VirtualKey.Number3:
                    case VirtualKey.Number4:
                    case VirtualKey.Number5:
                    case VirtualKey.Number6:
                    case VirtualKey.Number7:
                    case VirtualKey.Number8:
                    case VirtualKey.Number9:
                    case VirtualKey.NumberPad0:
                    case VirtualKey.NumberPad1:
                    case VirtualKey.NumberPad2:
                    case VirtualKey.NumberPad3:
                    case VirtualKey.NumberPad4:
                    case VirtualKey.NumberPad5:
                    case VirtualKey.NumberPad6:
                    case VirtualKey.NumberPad7:
                    case VirtualKey.NumberPad8:
                    case VirtualKey.NumberPad9:
                        break;
                    default:
                        e.Handled = true;
                        break;
                } 
            }
        }

        private void CboAssigneeOnDropDownOpened(object sender, object o)
        {
            _cacheAssignee = null;
        }

        private void CboProjectOnDropDownOpened(object sender, object o)
        {
            _cacheProject = null;
        }

        void CboCategory_DropDownOpened(object sender, object e)
        {
            _cacheCategory = null;
        }

        private void CancelButtonOnTapped(object sender, TappedRoutedEventArgs tappedRoutedEventArgs)
        {
            GlobalData.TemporaryTask = null;
            Navigator.Instance.HidePopup();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Allow to focus on the hold page a.k.a not show focus border on any other control.
            IsTabStop = true;

            var stTime = DateTime.Now.TimeOfDay;
            DataContext = e.Parameter == null ? new AddTaskViewModel(
                new TaskModel
                                  {
                                      ID = -1,
                                      StartDate = DateTime.Now.Date.ToString(),
                                      ProjectID = -1,
                                      StartTime = (int)stTime.TotalMinutes,
                                      EndDate = DateTime.Now.Date.ToString(),
                                      EndTime = (int)stTime.TotalMinutes + 60,
                                  }
                )
            : new AddTaskViewModel((TaskModel)e.Parameter);

        }

        private ItemCollection _cacheAssignee;
        private ItemCollection _cacheProject;
        private ItemCollection _cacheCategory;

        void CboAssignee_LayoutUpdated(object sender, object e)
        {
            if (CboAssignee.Items != null && CboAssignee.Items.Count > 0 && CboAssignee.Items != _cacheAssignee)
            {
                _cacheAssignee = CboAssignee.Items;
                Messenger.Instance.Notify(RebindCbo.RebindMember);
            }
        }

        void CboProject_LayoutUpdated(object sender, object e)
        {
            if (CboProject.Items != null && CboProject.Items.Count > 0 && CboProject.Items != _cacheProject)
            {
                _cacheProject = CboProject.Items;
                Messenger.Instance.Notify(RebindCbo.RebindProject);
            }
        }

        void CboCategory_LayoutUpdated(object sender, object e)
        {
            if (CboCategory.Items != null && CboCategory.Items.Count > 0 && CboCategory.Items != _cacheCategory)
            {
                _cacheCategory = CboCategory.Items;
                Messenger.Instance.Notify(RebindCbo.RebindCategory);
            }
        }

        private void backButton_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Navigator.Instance.HidePopup();
            GlobalData.TemporaryTask = null;
        }

        private void PageKeyDown(object sender, KeyRoutedEventArgs e)
        {
            if (e.Key == VirtualKey.Tab)
            {
                IsTabStop = false;
                // backButton.IsTabStop = true;
            }
            else if (e.Key == VirtualKey.Escape)
            {
                Navigator.Instance.HidePopup();
            }
        }

        private void Period_OnTextChanged(object sender, TextChangedEventArgs e)
        {
            UpdateEndtime();
        }

        private void StTime_OnValueChanged(object sender, EventArgs e)
        {
            UpdateEndtime(StTime.Value);
        }

        private void StDateOnValueChanged(object sender, EventArgs eventArgs)
        {
            UpdateEndtime(StTime.Value);
        }

        void Period_LayoutUpdated(object sender, object e)
        {
            UpdateEndtime(StTime.Value);
        }

        private void UpdateEndtime(object stTime = null)
        {
            var splitTime = 0.0;
            if (stTime == null)
            {
                var startTime = ((AddTaskViewModel)DataContext).Information.StartTime;
                if (startTime != null)
                    splitTime = (int)startTime;
            }
            else
            {
                splitTime = ((DateTime)stTime).Hour * 60 + ((DateTime)stTime).Minute;
            }

            if (!string.IsNullOrEmpty(Period.Text))
            {
                try
                {
                    splitTime += (int)((Convert.ToDouble(Period.Text)) * 60);
                }
                catch (Exception ex)
                {
                    LogManager.Instance.LogInfo("Cannot edit task end time " + ex);
                }
            }

            try
            {
                if (splitTime < 1440)
                {
                    ((AddTaskViewModel)DataContext).Information.EndTime = (int)splitTime; 
                }
                else
                {
                    ((AddTaskViewModel)DataContext).Information.EndTime = (int)splitTime%1440;
                }

                var oldDate = (DateTime)StDate.Value;
                DateTime newDate = oldDate.Add(new TimeSpan((int)Math.Floor(splitTime / 1440), 0, 0, 0));
                ((AddTaskViewModel)DataContext).Information.EndDate = newDate.ToString();
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogInfo("Cannot edit task end time " + ex);
            }

            try
            {
                var oldDate = (DateTime)StDate.Value;
                DateTime newDate = oldDate.Add(new TimeSpan((int)Math.Floor(splitTime / 1440), 0, 0, 0));
                ((AddTaskViewModel)DataContext).Information.EndDate = newDate.ToString();
            }
            catch (Exception ex)
            {
                LogManager.Instance.LogInfo("Cannot edit task end time " + ex);
            }
        }

        private void Period_OnGotFocus(object sender, RoutedEventArgs e)
        {
            Period.Text = "";
        }
    }
}
